/**
 * Wielobok.cpp
 *
 * Version: $Id: Wielobok.cpp 77 2012-01-07 11:54:01Z s8376@pjwstk.edu.pl $
 */
#include <iostream>
#include <cstdlib>
#include <cmath>
#include "Punkt.h"
#include "Wielobok.h"

using namespace std;

Wielobok::Wielobok(int pointNum)
{
    _checkVertexNum(pointNum);

    m_points = new Punkt*[pointNum];
    m_pointsNum = pointNum;
}
Wielobok::Wielobok(const Wielobok& ob)
{
    m_points = new Punkt*[ob.m_pointsNum];
    for (int i = 0; i < ob.m_pointsNum; i++) {
        m_points[i] = new Punkt(*ob.m_points[i]);
    }
}
Wielobok::~Wielobok()
{
    for (int i; i < m_pointsNum; i++) {
        delete m_points[i];
    }
    delete m_points;
    m_points = 0;
}
void Wielobok::_checkVertexesIsNotNull()
{
    for (int i = 0; i < m_pointsNum; i++) {
        if (m_points[i] == NULL) {
            cout << "Nie zadklarowano wszystkich punktów wieloboku" << endl;
            exit(1);
        }
    }
}
void Wielobok::_checkVertexNum(int n)
{
    if (n <= 0) {
        cout << "Numer wierzchołka musi być większy od 0" << endl;
        exit(1);
    } else if (n > m_pointsNum) {
        cout << "Numer wierzchołka musi być mniejszy lub równy " << m_pointsNum
                << endl;
        exit(1);
    }
}
void Wielobok::increase(int n)
{
    Punkt** pointsTmp = new Punkt*[m_pointsNum + n];

    for (int i = 0; i < m_pointsNum; i++) {
        pointsTmp[i] = m_points[i];
    }

    delete[] m_points;
    m_points = pointsTmp;

    m_pointsNum += n;
}
void Wielobok::decrease(int n)
{
    _checkVertexNum(m_pointsNum - n);

    for (int i = m_pointsNum - n; i < m_pointsNum; i++) {
        delete m_points[i];
    }

    Punkt** pointsTmp = new Punkt*[m_pointsNum - n];

    for (int i = 0; i < m_pointsNum - n; i++) {
        pointsTmp[i] = m_points[i];
    }

    delete[] m_points;
    m_points = pointsTmp;

    m_pointsNum -= n;
}
void Wielobok::set(Punkt *p, int pos)
{
    _checkVertexNum(pos);
    m_points[pos - 1] = p;
}
void Wielobok::deletepoint(int pos)
{
    _checkVertexNum(pos);
    delete m_points[pos - 1];
}
void Wielobok::show()
{
    _checkVertexesIsNotNull();

    cout << "Wielobok o " << m_pointsNum << " wierzchołkach" << endl;

    for (int i = 0; i < m_pointsNum; i++) {
        m_points[i]->show();
    }
}
double Wielobok::getParimeter()
{
    _checkVertexesIsNotNull();

    double circuit = 0;
    int point, nextPoint;

    for (int i = 0; i < m_pointsNum; i++) {
        if (i < (m_pointsNum - 1)) {
            point = i;
            nextPoint = i + 1;
        } else {
            point = 0;
            nextPoint = i;
        }

        circuit += sqrt(pow(m_points[nextPoint]->getX()
                - m_points[point]->getX(), 2) + pow(m_points[nextPoint]->getY()
                - m_points[point]->getY(), 2));
    }

    return circuit;
}
